<?php
/**
 * 图片画册
 * AUTHOR  : zlf
 * DateTime: 2022/06/18 09:00
 */

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\AlbumImgTitleModel;
use App\V3\V3_2_7\Services\PictureEditingService;
use App\V3\V3_2_7\Services\TextImageService;
use App\V3\V3_2_7\Services\TextImageTemplatesService;
use App\V3\V3_2_7\Services\ImageLabelService;
use App\V3\V3_2_7\Models\ImageLabelModel;
use App\V3\V3_2_7\Models\ContentTagsModel;
use App\V3\V3_2_7\Models\HcMaterielTypeModel;
use App\V3\V3_2_7\Models\GoodsAlbumModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use OSS\OssClient;
use App\V3\V3_2_7\Models\AdminAddendumModel;

class PictureEditingController extends BaseController
{
    protected $ossClient;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
        );
    }

    /**
     * 新建图片画册
     *
     * @param album_cover_img  画册封面
     * @param p_a_name         画册名称
     * @param mobile           联系电话
     * @param background_music 背景音乐
     * @param label_data       标签数据包
     * @param Album_imgs       画册内容图片(多图逗号分隔)
     * @param label_id         标签id
     */
    public function addPictureAlbum(Request $request)
    {
        $adminInfo = AdminAddendumModel::select('is_vip')->where(['main_id' => $this->getMainUserId()])->first()->toArray();
        if (!empty($adminInfo) && in_array($adminInfo['is_vip'], [1, 2])) {
            /*
             if($adminInfo['one_key_album_times'] != -1 && $total_num >= $adminInfo['one_key_album_times']){

             return $this->fail('','您一键生成商品画册次数，已达到设置数量！');
             }

             if($adminInfo['album_amount'] != -1 && $total_num >= $adminInfo['album_amount']){

             return $this->fail('','您生成商品画册彩页，已达到设置数量！');
             } */

        } else {
            return $this->fail('', '您还不是VIP会员，还不能创建图片画册！');
        }
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'p_a_name' => 'required',

        ], [
            'p_a_name.required' => '请填写画册名称',

        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => ''
            ]);
        }

        $imgs_data = self::handleImgsData($this->ossClient, $request, $this->getMainUserId());// 处理图片画册 封面、音乐 函数

        if ($imgs_data['code'] === 1) {

            return response()->json($imgs_data);

        } elseif ($imgs_data['code'] === 0) {

            $imgs_data = $imgs_data['data'];
        }

        $data['create_time'] = time();
        $data['update_time'] = time();

        $data = array_merge($data, $imgs_data);

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        if (isset($data['label_data'])) {

            if (!is_array($data['label_data'])) {

                $data['label_data'] = json_decode($data['label_data'], true);

            }

            $lData['label_data'] = $data['label_data'];
            unset($data['label_data']);
        } else {
            $lData['label_data'] = '';
        }

        DB::beginTransaction();
        try {
            $id = PictureEditingService::addPictureAlbum($data);
            if ($id) {

                if (!empty($lData['label_data'])) {

                    foreach ($lData['label_data'] as $k => $v) {

                        $updData['pa_id'] = $id;
                        $updData['label_name'] = $v['label_name'];
                        $updData['Album_imgs'] = $v['Album_imgs'];

                        $lCondition['id'] = $v['label_id'];
                        $lCondition['user_id'] = $this->getUserId();

                        $iInfo = ImageLabelService::getImageLabelInfo($lCondition);

                        if (!empty($iInfo['Album_imgs'])) {

                            $iInfo['Album_imgs'] = explode(',', $iInfo['Album_imgs']);
                            $v['Album_imgs'] = explode(',', $v['Album_imgs']);

                            $del_img_arr = array_merge(array_diff($iInfo['Album_imgs'], $v['Album_imgs']), array_diff($v['Album_imgs'], $iInfo['Album_imgs']));

                            if (!empty($del_img_arr) && is_array($del_img_arr)) {

                                foreach ($del_img_arr as $k => $v) {
                                    if (!empty($v)) {
                                        //删除oss里的文件
                                        $delOssRes = self::delOssFilePath($v, $this->ossClient, $this->getMainUserId());
                                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                    }
                                }
                            }
                        }
                        ImageLabelService::updImageLabel($lCondition, $updData);
                    }
                    unset($lData['label_data']);
                }
                unset($updData);
                $albumName = $data['p_a_name'] ?? '未命名';
                $logData = '画册名称：' . $albumName . '，创建成功！';
                $this->log('添加图片画册', $data, $logData);
                DB::commit();
                return response()->json(['code' => 0, 'msg' => '添加成功', 'data' => ['album_id' => $id]]);
            }
            return response()->json(['code' => 1, 'msg' => '添加失败', 'data' => '']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    /**
     * 删除图片画册
     * @param pa_ids 图片画册id(多个用逗号分开)
     */
    public function delPictureAlbum(Request $request)
    {

        $validator = Validator::make(
            $data = $request->all(), [
            'pa_ids' => 'required'
        ], [
            'pa_ids.required' => '请选择图片画册！'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
        }

        $condition['user_id'] = $this->getUserId();
        $pa_id_arr = explode(',', $data['pa_ids']);

        $pa_info = PictureEditingService::getPictureAlbumInfos($condition, $pa_id_arr);
        $bool = PictureEditingService::delPictureAlbum($condition, $pa_id_arr);
        $albumName = "";
        DB::beginTransaction();
        try {
            if ($bool) {
                if (!empty($pa_info)) {
                    foreach ($pa_info as $pkey => $pval) {
                        $albumName .= $pval['p_a_name'] . '、';
                        if (!empty($pval['album_cover_img'])) {//删除封面图片
                            //删除oss里的文件
                            $delOssRes = self::delOssFilePath($pval['album_cover_img'], $this->ossClient, $this->getMainUserId());
                            if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                        }
                        if (!empty($pval['background_music'])) {//删除背景音乐
                            //删除oss里的文件
                            $delOssRes = self::delOssFilePath($pval['background_music'], $this->ossClient, $this->getMainUserId());
                            if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                        }
                    }
                    $iList = ImageLabelModel::select('Album_imgs')->where($condition)->whereIn('pa_id', $pa_id_arr)->get();
                    if (!empty($iList)) {
                        ImageLabelModel::select('Album_imgs')->where($condition)->whereIn('pa_id', $pa_id_arr)->delete();
                        foreach ($iList as $ik => $iv) {

                            if (!empty($iv['Album_imgs'])) {//删除上传图片

                                $iv['Album_imgs'] = explode(',', $iv['Album_imgs']);

                                foreach ($iv['Album_imgs'] as $key => $val) {
                                    //删除oss里的文件
                                    $delOssRes = self::delOssFilePath($iv['Album_imgs'], $this->ossClient, $this->getMainUserId());
                                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                }
                            }
                        }
                    }
                }
                $this->log('删除图片画册', $data, '画册名称：' . $albumName . '，已删除！');
                DB::commit();
                return response()->json(['code' => 0, 'msg' => '删除成功', 'data' => '']);
            }
            return response()->json(['code' => 1, 'msg' => '删除失败', 'data' => '']);
        } catch (\Exception $e) {
            return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    /**
     * 删除首页画册
     * @param img_ids  图片画册id(多个用逗号分隔)
     * @param text_ids 文字画册id(多个用逗号分隔)
     * @param goods_album_ids 商品画册id(多个用逗号分隔)
     */
    public function delIndexAlbum(Request $request)
    {
        $condition['main_id'] = $this->getMainUserId();
        if (!empty($request->input('img_ids'))) {//首页删除图片画册

            $validator = Validator::make(
                $data = $request->all(), [
                'img_ids' => 'required'
            ], [
                'img_ids.required' => '请选择图片画册！'
            ]);
            //参数错误响应
            if ($info = $validator->errors()->first()) {
                return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
            }

            $albumName = "";
            $pa_id_arr = explode(',', $data['img_ids']);
            $pa_info = PictureEditingService::getPictureAlbumInfos($condition, $pa_id_arr);
            DB::beginTransaction();
            try {
                $bool = PictureEditingService::delPictureAlbum($condition, $pa_id_arr);
                if ($bool) {
                    if (!empty($pa_info)) {
                        foreach ($pa_info as $pkey => $pval) {
                            $albumName .= $pval['p_a_name'] . '、';
                            if (!empty($pval['album_cover_img'])) {//删除封面图片

                                //删除oss里的文件
                                $delOssRes = self::delOssFilePath($pval['album_cover_img'], $this->ossClient, $this->getMainUserId());
                                if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                            }

                            if (!empty($pval['background_music'])) {//删除背景音乐

                                //删除oss里的文件
                                $delOssRes = self::delOssFilePath($pval['background_music'], $this->ossClient, $this->getMainUserId());
                                if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                            }
                        }

                        $iList = ImageLabelModel::select('Album_imgs')->where($condition)->whereIn('pa_id', $pa_id_arr)->get();

                        if (!empty($iList)) {

                            ImageLabelModel::select('Album_imgs')->where($condition)->whereIn('pa_id', $pa_id_arr)->delete();

                            foreach ($iList as $ik => $iv) {

                                if (!empty($iv['Album_imgs'])) {//删除上传图片

                                    $iv['Album_imgs'] = explode(',', $iv['Album_imgs']);

                                    foreach ($iv['Album_imgs'] as $key => $val) {

                                        //删除oss里的文件
                                        $delOssRes = self::delOssFilePath($val, $this->ossClient, $this->getMainUserId());
                                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                    }
                                }
                            }
                        }
                    }
                    $this->log('删除图片画册', $data, '画册名称：' . $albumName . '，已删除！');
                    DB::commit();
                } else {
                    return response()->json(['code' => 1, 'msg' => '删除失败', 'data' => '']);
                }
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }
        if (!empty($request->input('text_ids'))) {//首页删除内容画册
            //参数验证
            $validator = Validator::make($data = $request->all(), [
                'text_ids' => 'required'
            ],
                [
                    'text_ids.required' => '缺少参数，文字画册id'
                ]);
            //参数错误响应
            if ($info = $validator->errors()->first()) {

                return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
            }
            $textName = "";
            $pa_id_arr = explode(',', $data['text_ids']);

            $res = TextImageService::getTextImageInfos($condition, $pa_id_arr);

            if (empty($res)) {

                return response()->json(['code' => 1, 'msg' => '要删除的文字画册，没找到!', 'data' => '']);

            }
            DB::beginTransaction();
            try {

                $bool = TextImageService::delTextImage($condition, $pa_id_arr);

                if ($bool) {

                    foreach ($res as $tk => $tv) {
                        $textName .= $tv['p_a_name'] . '、';
                        //删除oss里的文件
                        $delOssRes = self::delOssFilePath($tv['album_cover_img'], $this->ossClient, $this->getMainUserId());
                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                        //删除oss里的文件
                        $delOssRes = self::delOssFilePath($tv['background_music'], $this->ossClient, $this->getMainUserId());
                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                    }

                    $t_res = TextImageTemplatesService::getTextImageTemplatesInfos($condition, $pa_id_arr);

                    if (!empty($t_res)) {
                        //删除画册对应的内容模板
                        TextImageTemplatesService::delContentTempLates($condition, $pa_id_arr);

                        foreach ($t_res as $tik => $tiv) {

                            if (!empty($tiv['temp_img_video_01'])) {

                                $tiv['temp_img_video_01'] = explode(",", $tiv['temp_img_video_01']);

                                foreach ($tiv['temp_img_video_01'] as $iv1k => $iv1v) {//删除素材1的文件
                                    //删除oss里的文件
                                    $delOssRes = self::delOssFilePath($iv1v, $this->ossClient, $this->getMainUserId());
                                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                }
                            }
                            if (!empty($tiv['temp_img_video_02'])) {//删除素材2的文件

                                $tiv['temp_img_video_02'] = explode(",", $tiv['temp_img_video_02']);

                                foreach ($tiv['temp_img_video_02'] as $iv2k => $iv2v) {

                                    //删除oss里的文件
                                    $delOssRes = self::delOssFilePath($iv2v, $this->ossClient, $this->getMainUserId());
                                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                }
                            }
                        }

                    }

                    ContentTagsModel::where($condition)->whereIn('pa_id', $pa_id_arr)->delete();
                    $this->log('删除文字图片画册', $data, '画册名称：' . $textName . '，已删除！');
                    DB::commit();
                } else {
                    return response()->json(['code' => 1, 'msg' => '删除失败', 'data' => '']);
                }

            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }

        if (!empty($request->input('goods_album_ids'))) {
            $goodsName = "";
            $gCondition['main_id'] = $this->getMainUserId();
            $album_ids_arr = explode(',', $request->input('goods_album_ids'));
            $gList = GoodsAlbumModel::select(
                "p_a_name",
                "album_cover_img",
                "background_music"
            )->where($gCondition)
                ->whereIn('id', $album_ids_arr)->get();
            if (empty($gList)) return $this->fail('', '没有找到，要删除的商品画册！');
            DB::beginTransaction();
            try {

                GoodsAlbumModel::where($gCondition)->whereIn('id', $album_ids_arr)->delete();
                HcMaterielTypeModel::where($gCondition)->whereIn('album_id', $album_ids_arr)->delete();

                foreach ($gList as $gv) {
                    $goodsName .= $gv['p_a_name'] . '、';
                    if (!empty($gv['album_cover_img'])) {
                        //删除oss里的文件
                        $delOssRes = self::delOssFilePath($gv['album_cover_img'], $this->ossClient, $this->getMainUserId());
                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                    }

                    if (!empty($gv['background_music'])) {

                        //删除oss里的文件
                        $delOssRes = self::delOssFilePath($gv['background_music'], $this->ossClient, $this->getMainUserId());
                        if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                    }
                }
                $this->log('删除商品画册', $request->input('goods_album_ids'), '画册名称：' . $goodsName . '已删除！');
                DB::commit();
                return $this->success();

            } catch (\Exception $e) {
                DB::rollBack();
                Log::debug('删除商品画册异常');
                return $this->fail('', $e->getMessage());
            }

        }

        return response()->json(['code' => 0, 'msg' => '删除成功', 'data' => '']);
    }

    /**
     * 删除图片画册上传的图片
     *
     * @param del_img_paths  要删除的图片路径
     * @param label_id       标签id
     */
    public function delAlbumImgs(Request $request)
    {

        $validator = Validator::make(
            $data = $request->all(), [
            'del_img_paths' => 'required'
        ], [
            'del_img_paths.required' => '请选择,要删除的图片'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => ''
            ]);
        }

        $img_paths = explode(',', $data['del_img_paths']);

        DB::beginTransaction();
        try {

            if (!empty($data['label_id'])) {

                $condition['id'] = $data['label_id'];
                $info = ImageLabelService::getImageLabelInfo($condition);
                $Album_imgs = explode(',', $info['Album_imgs']);
                $arr = array_merge(array_diff($Album_imgs, $img_paths), array_diff($img_paths, $Album_imgs));

                $update_data['Album_imgs'] = implode(',', $arr);

                $update_data['update_time'] = time();

                $bool = ImageLabelService::updImageLabel($condition, $update_data);

                if ($bool) {

                    if (!in_array($Album_imgs[0], $arr) && $info['album_cover_img'] == $Album_imgs[0]) {

                        $p_data['album_cover_img'] = $arr[0];
                        $PCondition['id'] = $info['pa_id'];
                        PictureEditingService::updateAlbumImgs($PCondition, $p_data);
                    }

                    $this->log('删除图片画册图片', $bool);
                }
            }
            if (is_array($img_paths)) {
                foreach ($img_paths as $key => $val) {
                    //删除oss里的文件
                    $delOssRes = self::delOssFilePath($val, $this->ossClient, $this->getMainUserId());
                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                }

            } else {
                //删除oss里的文件
                $delOssRes = self::delOssFilePath($data['del_img_paths'], $this->ossClient, $this->getMainUserId());
                if (!empty($delOssRes)) return $this->fail('', $delOssRes);
            }
            AlbumImgTitleModel::query()
              ->whereIn('album_img',$img_paths)->update(['delete_flag'=>1]);
            DB::commit();
            return response()->json(['code' => 0, 'msg' => '删除成功', 'data' => '']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    /**
     * 修改图片画册
     *
     * @param album_cover_img  画册封面
     * @param p_a_name         画册名称
     * @param mobile           联系电话
     * @param background_music 背景音乐
     * @param pa_id            图片画册id
     * @param label_data       标签数据包
     * @param label_id         标签
     * @param Album_imgs       画册内容图片(多图逗号分隔)
     */
    public function updatePictureAlbum(Request $request)
    {

        $validator = Validator::make(
            $data = $request->all(), [
            'pa_id' => 'required'
        ], [
            'pa_id.required' => '画册的id,不能为空!'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
        }
        /* $json='[{"label_id":3,"label_name":"掌上网络038","Album_imgs":"38.png,38.png"},{"label_id":4,"label_name":"掌上网络044","Album_imgs":"44.png,44.png"}]';

        $data['label_data']=json_decode($json,true); */

        $condition['id'] = $data['pa_id'];


        unset($data['pa_id']);

        $info = PictureEditingService::getPictureAlbumInfo($condition);

        if (empty($info)) {

            return response()->json(['code' => 1, 'msg' => '修改的图片画册，没有找到！', 'data' => '']);
        }

        $imgs_data = self::handleImgsData($this->ossClient, $request, $this->getMainUserId());

        if ($imgs_data['code'] === 1) {

            return response()->json($imgs_data);

        } elseif ($imgs_data['code'] === 0) {

            $imgs_data = $imgs_data['data'];
        }

        $data['update_time'] = time();

        $data = array_merge($data, $imgs_data);

        if (!empty($data['p_a_name']))
            $data['p_a_name'] = $data['p_a_name'];

        if (!empty($data['mobile'])) {

            $data['mobile'] = $data['mobile'];
        }

        if (isset($data['label_data'])) {

            if (!is_array($data['label_data'])) {

                $data['label_data'] = json_decode($data['label_data'], true);

            }

            $lData['label_data'] = $data['label_data'];
            unset($data['label_data']);
        } else {
            $lData['label_data'] = '';
        }
        DB::beginTransaction();
        try {
            $bool = PictureEditingService::updateAlbumImgs($condition, $data);

            if ($bool) {

                if (!empty($request->file('album_cover_img'))) {

                    //删除oss里的文件
                    $delOssRes = self::delOssFilePath($info['album_cover_img'], $this->ossClient, $this->getMainUserId());
                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                }

                if (!empty($request->file('background_music'))) {
                    //删除oss里的文件
                    $delOssRes = self::delOssFilePath($info['background_music'], $this->ossClient, $this->getMainUserId());
                    if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                }

                if (!empty($lData['label_data'])) {

                    foreach ($lData['label_data'] as $k => $v) {

                        $lCondition['id'] = $v['label_id'];

                        if (isset($v['Album_imgs'])) {

                            $updData['Album_imgs'] = $v['Album_imgs'];
                        }
                        if (isset($v['label_name'])) {

                            $updData['label_name'] = $v['label_name'];
                        }
                        $info = ImageLabelService::getImageLabelInfo($lCondition);

                        $bol = ImageLabelService::updImageLabel($lCondition, $updData);

                        if ($bol) {

                            if (!empty($info)) {

                                $info['Album_imgs'] = explode(',', $info['Album_imgs']);
                                $v['Album_imgs'] = explode(',', $v['Album_imgs']);

                                $del_img_arr = array_merge(array_diff($info['Album_imgs'], $v['Album_imgs']), array_diff($v['Album_imgs'], $info['Album_imgs']));

                                if (!empty($del_img_arr) && is_array($del_img_arr)) {

                                    foreach ($del_img_arr as $k => $v) {

                                        if (!empty($v)) {
                                            //删除oss里的文件
                                            $delOssRes = self::delOssFilePath($v, $this->ossClient, $this->getMainUserId());
                                            if (!empty($delOssRes)) return $this->fail('', $delOssRes);
                                        }
                                    }
                                }
                            }

                        }
                    }
                    unset($lData);
                }
                unset($updData);
                DB::commit();
                $this->log('编辑图片画册', $data, '画册名称：' . $info['p_a_name'] . ' 信息已更新！');
                return response()->json(['code' => 0, 'msg' => '编辑成功', 'data' => '']);
            }
            return response()->json(['code' => 1, 'msg' => '编辑失败', 'data' => '']);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => $e->getMessage(), 'data' => '']);
        }

    }

    /**
     * 图片画册列表
     * @param curr_page  页码
     */
    public function getPictureAlbumList(Request $request)
    {
        $adminInfo = AdminAddendumModel::select('is_vip', 'album_page_amount')->where(['main_id' => $this->getMainUserId()])->first()->toArray();

        if (!empty($adminInfo) && in_array($adminInfo['is_vip'], [1, 2])) {

            if ($adminInfo['album_page_amount'] != -1 && $request->current_page >= $adminInfo['album_page_amount']) {

                return response()->json([
                    'code' => 1,
                    'msg' => '您当前彩页超出限制' . $adminInfo['album_page_amount'] . '页，超出部分未生成彩页',
                    'data' => '',
                ]);
            }
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '您还不是VIP会员，不能展示彩页！',
                'data' => '',
            ]);
        }
        $condition['pa.main_id'] = $this->getMainUserId();
        $currentPage = !empty($request->input('curr_page')) ? $request->input('curr_page') : 1;
        $pageSize = !empty($request->input('page_size')) ? $request->input('page_size') : 20;
        $list = PictureEditingService::getPictureAlbumList($condition, $currentPage, $pageSize);

        if (!empty($list['data'])) {
            foreach ($list['data'] as $k => $val) {

                if (!empty($val['album_cover_img'])) {

                    $list['data'][$k]['album_cover_img'] = self::addWatermark($this->ossClient, $val['album_cover_img'], $this->getMainUserId());//添加水印
                }

                $iCondition['pa_id'] = $val['id'];
                $iList = ImageLabelService::getImageLabelLists($iCondition);

                if (!empty($iList['data'])) {
                    foreach ($iList['data'] as $ik => $iv) {
                        if (!empty($iv['Album_imgs'])) {
                            $list['data'][$k]['label_data'][$ik]['id'] = $iv['id'];
                            $list['data'][$k]['label_data'][$ik]['pa_id'] = $iv['pa_id'];
                            $list['data'][$k]['label_data'][$ik]['is_top'] = $iv['is_top'];
                            $list['data'][$k]['label_data'][$ik]['sort_number'] = $iv['sort_number'];
                            $list['data'][$k]['label_data'][$ik]['label_name'] = $iv['label_name'];
                            $list['data'][$k]['label_data'][$ik]['create_time'] = date('Y-m-d H:i:s', $iv['create_time']);
                            $list['data'][$k]['label_data'][$ik]['update_time'] = date('Y-m-d H:i:s', $iv['update_time']);

                            $imgArr = explode(',', $iv['Album_imgs']);

                            foreach ($imgArr as $iak => $iav) {

                                $imgArr[$iak] = self::addWatermark($this->ossClient, $iav, $this->getMainUserId());
                            }

                            $list['data'][$k]['label_data'][$ik]['Album_imgs'] = $imgArr;
                        }
                    }
                } else {

                    $list['data'][$k]['label_data'] = [];
                }
            }

        }
        return response()->json(['code' => 0, 'msg' => '查询成功', 'data' => $list]);
    }

    /**
     * 画册首页-图片画册和文字画册
     */
    public function getImagesTextAlbumList(Request $request)
    {

        $condition['pa.main_id'] = $this->getMainUserId();

        $currentPage = !empty($request->input('curr_page')) ? $request->input('curr_page') : 1;
        $pageSize = !empty($request->input('page_size')) ? $request->input('page_size') : 20;
        $p_list = PictureEditingService::getPictureAlbumList($condition, $currentPage, $pageSize);

        unset($condition['pa.main_id']);

        $condition['ti.main_id'] = $this->getMainUserId();
        $t_list = TextImageService::getTextImageList($condition, $currentPage, $pageSize);

        $g_list = GoodsAlbumModel::select('id', 'p_a_name', 'album_cover_img', 'flag', 'create_time')
            ->where(['main_id' => $this->getMainUserId()])
            ->where('is_del', 0)
            ->get()->toArray();

        $data = array_merge($p_list['data'], $t_list['data'], $g_list);

        $time_arr = [];

        // 取得列的列表
        foreach ($data as $key => $val) {

            $time_arr[$key] = $val['create_time'];

            if (!empty($val['album_cover_img'])) {

                $data[$key]['album_cover_img'] = self::addWatermark($this->ossClient, $val['album_cover_img'], $this->getMainUserId());
            }
            if (!empty($val['flag'])) {
                switch ($val['flag']) {
                    case 'img':
                        $data[$key]['flag_name'] = '图片类型';
                        break;
                    case 'text':
                        $data[$key]['flag_name'] = '文字画册类型';
                        break;
                    case 'goods':
                        $data[$key]['flag_name'] = '商品画册类型';
                        break;
                }
            } else {
                $data[$key]['flag_name'] = '未知类型';
            }
        }
        array_multisort($time_arr, SORT_DESC, $data);
        $data = ['data' => $data];
        return response()->json(['code' => 0, 'msg' => '查询成功', 'data' => $data]);

    }

    /**
     * 查询画册信息
     * @param pa_id 画册的id
     */
    public function getPictureAlbumInfo(Request $request)
    {

        $validator = Validator::make(
            $data = $request->all(), [
            'pa_id' => 'required'
        ], [
            'pa_id.required' => '画册的id,不能为空!'
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {

            return response()->json(['code' => 1, 'msg' => $info, 'data' => '']);
        }

        $condition['id'] = $data['pa_id'];
        $condition['main_id'] = $this->getMainUserId();

        unset($data['pa_id']);

        $info = PictureEditingService::getPictureAlbumInfo($condition);

        if (empty($info)) {

            return response()->json(['code' => 1, 'msg' => '查询的图片画册，没有找到！', 'data' => '']);
        }

        if (!empty($info['album_cover_img'])) {

            $info['album_cover_img'] = self::addWatermark($this->ossClient, $info['album_cover_img'], $info['main_id']);
        }

        $condition['pa_id'] = $data['pa_id'];

        unset($condition['id']);

        $iList = ImageLabelService::getImageLabelLists($condition);

        if (!empty($iList)) {
            foreach ($iList as $ik => $iv) {
                if (!empty($iv['Album_imgs'])) {
                    $info['label_data'][$ik]['id'] = $iv['id'];
                    $info['label_data'][$ik]['pa_id'] = $iv['pa_id'];
                    $info['label_data'][$ik]['label_name'] = $iv['label_name'];
                    //$info['label_data'][$ik]['Album_imgs'] = explode(',',$iv['Album_imgs']);
                    $imgArr = explode(',', $iv['Album_imgs']);

                    foreach ($imgArr as $iak => $iav) {

                        $imgArr[$iak] = self::addWatermark($this->ossClient, $iav, $this->getMainUserId());
                    }

                    $info['label_data'][$ik]['Album_imgs'] = $imgArr;

                }
            }
        } else {
            $info['label_data'] = [];
        }

        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        $info['update_time'] = date('Y-m-d H:i:s', $info['update_time']);

        $this->log('图片画册信息，查询成功', $info);
        return response()->json(['code' => 0, 'msg' => '查询成功', 'data' => $info]);

    }

    /**
     * 处理图片画册 封面、音乐、上传多图片 函数
     *
     */
    static public function handleImgsData($client, $request, $mainId)
    {
        $data = [];
        $data['album_cover_img'] = "";
        if (!empty($cover_img_files = $request->file('album_cover_img'))) {
            $res = self::handlePicFormat($cover_img_files, 'p', '封面格式,不正确！');//判断文件格式

            if (!empty($res)) return $res;

            if ($cover_img_files->isValid()) {

                $ac_img_path = $cover_img_files->store('huace/imgs/img/' . date('Y') . '-' . date('m') . '-' . date('d'));

                $imgRes = self::addOssUploadImg($mainId, $client, $cover_img_files, $ac_img_path);

                if ($imgRes['code'] === 0) {
                    $data['album_cover_img'] = $imgRes['data'];
                } else {
                    return $imgRes;
                }

            } else {

                return [
                    'code' => 1,
                    'msg' => '画册封面，上传失败！',
                    'data' => ''
                ];

            }

        } elseif (!empty($request->input('album_cover_img'))) {

            $data['album_cover_img'] = $request->input('album_cover_img');
        } else {
            unset($data['album_cover_img']);
        }

        if (!empty($music_files = $request->file('background_music'))) {

            $res = self::handlePicFormat($music_files, 'm', '音乐格式,不正确！');//判断文件格式

            if (!empty($res)) return $res;

            if ($music_files->isValid()) {

                $music_path = $music_files->store('huace/imgs/music/' . date('Y') . '-' . date('m') . '-' . date('d'));
                $imgRes = self::addOssUploadImg($mainId, $client, $music_files, $music_path);
                if ($imgRes['code'] === 0) {
                    $data['background_music'] = $imgRes['data'];
                } else {
                    return $imgRes;
                }
            } else {

                return [
                    'code' => 1,
                    'msg' => '背景音乐，上传失败！',
                    'data' => ''
                ];

            }

        } elseif (!empty($request->input('background_music'))) {

            $data['background_music'] = $request->input('background_music');
        } else {
            $data['background_music'] = "";
        }
        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    /**
     * 单文件上传
     *
     * @param hc_img 文件名
     * @param label_id 图片画册id
     */
    public function upload(Request $request)
    {

        if (empty($request->input('label_id'))) {
            return response()->json(['code' => 1, 'msg' => '图片标签id,不能为空！', 'data' => '']);
        }

        $condition['id'] = $request->input('label_id');

        $info = ImageLabelService::getImageLabelInfo($condition);

        if (empty($info)) {

            return response()->json(['code' => 1, 'msg' => '画册标签,不存在！', 'data' => '']);
        }

        if (!empty($hc_file = $request->file('hc_img'))) {

            $imgs_str = '';

            foreach ($hc_file as $v) {

                if ($v->isValid()) {

                    $res = self::handlePicFormat($v, 'p', '图片格式，不正确！');

                    if (!empty($res)) return response()->json($res);

                    $img_path = $v->store('huace/imgs/img/' . date('Y') . '-' . date('m') . '-' . date('d'));

                    $imgRes = self::addOssUploadImg($this->getMainUserId(), $this->ossClient, $v, $img_path);

                    if ($imgRes['code'] == 1) return response()->json($imgRes);

                    $imgs_str .= $imgRes['data'] . ',';

                } else {

                    return response()->json(['code' => 1, 'msg' => '上传失败', 'data' => '']);
                }
            }
            $updData['Album_imgs'] = substr($imgs_str, 0, strrpos($imgs_str, ","));

            if (!empty($info['Album_imgs'])) {

                $iData['Album_imgs'] = $info['Album_imgs'] . ',' . $updData['Album_imgs'];
            } else {
                $iData['Album_imgs'] = $updData['Album_imgs'];
            }

            ImageLabelService::updImageLabel($condition, $iData);

            return response()->json(['code' => 0, 'msg' => '上传成功', 'data' => ['hc_img_path' => config('app.aliyun_oss_bucket_url') . $updData['Album_imgs'], 'label_id' => $request->input('label_id')]]);
        } else {
            return response()->json(['code' => 1, 'msg' => '请选择图片上传', 'data' => '']);

        }
    }

    /**
     * 添加水印
     * @param unknown $file
     */
    static public function addWatermark($client, $file, $mainId)
    {
        if (empty($file)) return $file;
        $adminInfo = AdminAddendumModel::select('clear_watermark_or_not')->where(['main_id' => $mainId])->first();

        if ($adminInfo['clear_watermark_or_not'] == 1) {

            return $file;
        } else {
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo = $client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                if (strpos($imgInfo['content-type'], 'image/') !== false) {

                    return $file = $file . config('app.aliyun_oss_img_watermark');
                }

                return $file;
            } catch (\Exception $e) {

            }
        }

    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId, $client, $file, $path)
    {

        $res = handleUploadFileType($file);
        if (!empty($res)) return $res;
        $size = $file->getSize();
        $result = saveFileSize(['main_id' => $mainId], $size, $path);
        if ($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/' . $path;
            $ossPath = ltrim($fullPath, './');
            $path = public_path() . $fullPath;
            $client->uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url') . $fullPath;
            return ["code" => 0, "msg" => "success", "data" => $url];

        } catch (\Exception $e) {

            return ["code" => 1, "msg" => "OSS系统，上传图片失败！", "data" => ""];
        }
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file, $client, $mainId)
    {

        if (empty($file)) return $file;

        DB::beginTransaction();
        try {
            $delPath = strstr($file, 'uploads/');
            $imgInfo = $client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
            AdminAddendumModel::where(['main_id' => $mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
            $client->deleteObject(config('app.aliyun_oss_bucket'), $delPath);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

        }

    }

    /**
     * 处理图片和视频格式
     */
    static public function handlePicFormat($files, $flag, $msg)
    {

        $pic_video_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts,
                                flash,mpeg,mpeg-2,mpeg-4,midi,wmv,asf,asx,rm,rmvb,mp4,3gp,mov,m4v,avi,dat,mkv,flv,vob,
                                bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,
                                ufo,eps,ai,raw,wmf,webp,avif,apng';

        $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';

        $music_format = 'mp3,aac,wav,wma,cda,flac,m4a,mid,mka,mp2,mpa,mpc,ape,ofr,ogg,ra,wv,ac3,dts';

        $ext = $files->extension();

        $ext = strtolower($ext);

        if ($flag == 'm') {

            $pic_video_format_arr = explode(',', $music_format);

        } elseif ($flag == 'p') {

            $pic_video_format_arr = explode(',', $pic_format);

        } else {

            $pic_video_format_arr = explode(',', $pic_video_format);
        }

        if (!in_array($ext, $pic_video_format_arr)) {

            return ['code' => 1, 'msg' => $msg, 'data' => ''];
            die;
        }

    }
}
